package com.ruohi.util.cdn;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

/**
 * @author Halley
 */
public class Post {
	private final String username;
	private final String password;
	private final String task;

	public Post(String username, String password, String task) {
		super();
		this.username = username;
		this.password = password;
		this.task = task;
	}

	public void startRefresh() throws ClientProtocolException, IOException {
		HttpClient httpClient = new DefaultHttpClient();//创建一个HttpClient即http的客户端
		HttpPost httpPost = new HttpPost("https://r.chinacache.com/content/refresh");//此处的"https://r.chinacache.com/content/refresh"为访问请求URL

		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		formparams.add(new BasicNameValuePair("username", username));//创建一个请求头的字段，比如content-type,text/plain
		formparams.add(new BasicNameValuePair("password", password));
		formparams.add(new BasicNameValuePair("task", task));
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,"UTF-8");//对自定义请求头进行URL编码
		httpPost.setEntity(entity);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = httpClient.execute(httpPost, responseHandler);
		httpClient.getConnectionManager().shutdown();
		System.out.println(responseBody);
	}

	public static void main(String[] args) throws ClientProtocolException,IOException {
		
		String url = "\"http://www.xxx.com/logo.gif\",\"http://www.xxx.com/\"";
		String dirs = "\"http://www.xxx.com/imgs/\",\"http://www.xxx.com/html/\"";
		String callurl = "\"http://xxx.com/listener\"";
		String callemail = "\"x@x.com\"";
		boolean callacptNotice = true;
		String task = "{\"urls\":["+url+"], " +
				"\"dirs\":["+dirs+"]," +
				"\"callback\":{\"url\":"+callurl+", \"email\":["+callemail+"],\"acptNotice\":"+callacptNotice+"}}";
		Post ref = new Post("jerry", "cc_123456", task);
		ref.startRefresh();
	}
}
